﻿using rbac.Domain.Entity;
using rbac.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rbac.Domain.Impl
{
    public class RolePermissionRepository: IRolePermissionRepository
    {
        private readonly RbacContext _context;

        public RolePermissionRepository(RbacContext context)
        {
            _context = context;
        }
        /// <summary>
        /// 为角色
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="permissionIdList"></param>
        /// <returns></returns>
        public int DistributeRolePermission(int roleId, List<int> permissionIdList)
        {
            if(permissionIdList.Count<=0)
            {
                return 0;
            }
            //最新的权限列表
            List<RolePermission> list = permissionIdList.Select(c => new RolePermission
            {
                 RoleId = roleId,
                  PermissionId = c

            }).ToList();
            //查询原有的权限列表(暴力做法)
            var oldPermissions = _context.RolePermissions.Where(c => c.RoleId == roleId);
            //移除原有的权限
            _context.RolePermissions.RemoveRange(oldPermissions);
            _context.RolePermissions.AddRange(list);

          /*  //获取需要被移除的权限 Except(差集)
            var needDeleteList = oldPermissions.Except(list);//去差集
            _context.RolePermissions.RemoveRange(needDeleteList);
            var needAddList = list.Except(oldPermissions);//新增的权限
            _context.RolePermissions.AddRange(needAddList);*/


     
            return _context.SaveChanges();
            
        }
        public List<Permission> GetPermissionByRoleId(int roleId)
        {
            //根据角色ID获取权限IDList
            var permissionIdList = _context.RolePermissions.Where(c => c.RoleId == roleId).Select(c => c.PermissionId);
            return _context.Permissions.Where(c => permissionIdList.Contains(c.Id)).ToList();
        }
    }
}
